package com.fjsh.config.verssion;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.mvc.condition.RequestCondition;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ApiRequestCondition implements RequestCondition<ApiRequestCondition> {

    /**
     * 从URL中提取版本部分，例如：[v0-9]
     */
    private final static Pattern VERSION_PREFIX_PATTERN = Pattern.compile("v(\\d+)");

    private int apiVersion;

    public ApiRequestCondition(int apiVersion) {
        this.apiVersion = apiVersion;
    }

    public int getApiVersion() {
        return apiVersion;
    }

    @Override
    public ApiRequestCondition combine(ApiRequestCondition other) {
        // 采用最后定义优先原则，则方法上的定义覆盖类上面的定义
        return new ApiRequestCondition(other.getApiVersion());
    }

    @Override
    public int compareTo(ApiRequestCondition other, HttpServletRequest request) {
        // 对符合请求版本的版本号进行排序
        return other.getApiVersion() - this.apiVersion;
    }

    @Override
    public ApiRequestCondition getMatchingCondition(HttpServletRequest request) {
        // 设置默认版本号，请求版本号错误时使用最新版本号的接口
        Integer version = Integer.MAX_VALUE;
        // 获取请求版本号-先从请求头获取版本号，请求头为空的话从url路劲获取版本号
        String apiVersion = Optional.ofNullable(request.getHeader("api-version")).orElse(request.getRequestURI()).intern();
        // 校验
        if (!StringUtils.isEmpty(apiVersion)) {
            Matcher matcher = VERSION_PREFIX_PATTERN.matcher(apiVersion);
            if (matcher.find()) {
                version = Integer.valueOf(matcher.group(1));
            }
        }
        // 当应用比配置更大的版本号时，它将采取提取
        if (version >= this.apiVersion) {
            return this;
        }
        return null;
    }
}
